package fr.playsoft.psas.listview;

import java.util.Arrays;
import java.util.LinkedList;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import fr.playsoft.psas.R;
import fr.playsoft.psas.listview.PullToRefreshListView2.OnRefreshListener2;

public class PullToRefreshActivity2 extends ListActivity {
	
	public static final String TAG = "Pull2Refresh";
	
    private LinkedList<String> mListItems;
    
    private PullToRefreshListView2 mList;
    
    private static final int TIME_WAIT_FOR_HIDE_REFRESH_PANEL = 3000;
	private Thread mHideRefreshPanelThread;
	private int mWaitingRefreshTime = 0;
	private ArrayAdapter<String> mAdapter;
    
	final Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.i(TAG, "handleMessage @int=" + msg.what + 
					" @wait=" + mList.isWaitingForPressRefresh() + 
					" @mRefreshState=" + mList.mRefreshState + 					
					" ============================");
			//switch(msg.what) {
			//case 0:
				//CLog.i(TAG, "mHideRefreshPanelThread mList.onHideRefreshPanel()");
			if(mList.isWaitingForPressRefresh()) {
				mList.onHideRefreshPanel();
				mWaitingRefreshTime = 0;
			}

			//}
		}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pull_to_refresh2);
        
        mList = (PullToRefreshListView2) getListView();
        // Set a listener to be invoked when the list should be refreshed.
        mList.setOnRefreshListener(new OnRefreshListener2() {
            @Override
            public void onRefresh() {
                // Do work to refresh the list here.
                new GetDataTask().execute();
            }
        });

        mListItems = new LinkedList<String>();
        mListItems.addAll(Arrays.asList(mStrings));

        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
        
        setListAdapter(mAdapter);
        
        mHideRefreshPanelThread = new Thread() {
        	public void run() {
        		mWaitingRefreshTime = 0;
        		while(true) {
    				if(!mList.isWaitingForPressRefresh()) {
    					mWaitingRefreshTime = 0;
    				}
    				else {
    					if(mWaitingRefreshTime < 3)
    						Log.i(TAG, "mHideRefreshPanelThread @time=" + mWaitingRefreshTime);
    					if(mWaitingRefreshTime < TIME_WAIT_FOR_HIDE_REFRESH_PANEL) {
    						try {
								Thread.sleep(100);
								mWaitingRefreshTime += 100;
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
    					}
    					else if(mWaitingRefreshTime >= TIME_WAIT_FOR_HIDE_REFRESH_PANEL){
    						Message msg = Message.obtain();
    			            msg.what = mWaitingRefreshTime;
    						myHandler.sendMessage(msg); 
    						mWaitingRefreshTime = 0;
    					}
    					
    				}
        		}
        	}
        };
        mHideRefreshPanelThread.start();
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                ;
            }
            return mStrings;
        }

        @Override
        protected void onPostExecute(String[] result) {
            mListItems.addFirst("Added after refresh...");

            // Call onRefreshComplete when the list has been refreshed.
            mList.onRefreshComplete();

            super.onPostExecute(result);
        }
    }

    private String[] mStrings = {
            "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam",
            "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis",
            "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
            "Allgauer Emmentaler"};
}
